;(function() {

	'use strict';
	angular.module('services.omdisplay.sysBusStat')
		.service('sumstatistics', Sumstatistics)
		.factory('sumStatisticsServe', sumStatisticsServe)
		.factory('sumStatisticsFn', sumStatisticsFn)
		.service('sumStatisticsData', sumStatisticsData)
		.service('QueryResultService', QueryResultService);

	function Sumstatistics(sumStatisticsServe, sumStatisticsFn, sumStatisticsData, QueryResultService) {
		this.sumStatisticsServe = sumStatisticsServe;
		this.sumStatisticsFn = sumStatisticsFn;
		this.sumStatisticsData = sumStatisticsData;
		this.queryResultService = QueryResultService;
	}

	Sumstatistics.$inject = ['sumStatisticsServe', 'sumStatisticsFn', 'sumStatisticsData', 'QueryResultService'];

	function QueryResultService() {
		this.tradeType = [];
		this.agencys = [];
		this.accessChannels = [];
	}

	function sumStatisticsData(sumStatisticsFn, CoreService) {
		return {
			getPageBindObj : getPageBindObj,
			getTradeState : getTradeState,
			getSendData : getSendData
		};
		//获取页面绑定对象
		function getPageBindObj() {
			var year = new Date().getFullYear();
			var month = new Date().getMonth();
			var day = new Date().getDate() - 1;
			//页面绑定对象
			return {
				businessLine: '', //业务线
				channel: [], //接入渠道
				organization: [], //机构
				provinceCode: [], //省份
				tradeStateCode: '00', //交易状态
				tradeTypeCode: [], //交易类型
				timeType: '1',
				startTime: new Date(year, month, day),
				startQuarter: '',
				endTime: new Date(year, month, day),
				endQuarter: '',
				diffTime: 'false',
				diffPro: '1' //2:全部(分省)  1:全部(汇总)
			};
		}
		//获取交易状态
		function getTradeState() {
			return [{
				tradeStateCode: '00',
				tradeStateName: '充值成功'
			}, {
				tradeStateCode: '01',
				tradeStateName: '交易失败'
			}];
		}
		/**
		 * @function [getSendData]  格式化页面绑定对象，传递后端
		 * @param  {[object]} pageBindObj 页面绑定对象
		 */
		function getSendData(pageBindObj) {
			var sendObj = {
				businessLine: [],
				businessLineName: [],
				channel: [],
				organization: [], //机构
				provinceCode: [],
				provinceName:[],
				tradeStateCode: [],
				tradeStateName: [],
				tradeTypeCode: [],
				timeType: '',
				startTime: '',
				startQuarter: '',
				endTime: '',
				endQuarter: '',
				diffTime: '',
				diffPro: '1'
			};
			//业务线
			if (pageBindObj.businessLine === '' || pageBindObj.businessLine === undefined) {
				sendObj.businessLine.length = 0;
				sendObj.businessLineName.length = 0;
			} else {
				sendObj.businessLine.push(pageBindObj.businessLine.businessLineCode);
				sendObj.businessLineName.push(pageBindObj.businessLine.businessLineName);
			}
			//交易状态
			if (pageBindObj.tradeStateCode === '' || pageBindObj.tradeStateCode === undefined) {
				sendObj.tradeStateCode.length = 0;
			} else {
				sendObj.tradeStateCode.push(pageBindObj.tradeStateCode);
			}
			//交易类型
			sendObj.tradeTypeCode = pageBindObj.tradeTypeCode.map(function(td) {
				return td.tradeTypeCode;
			});

			sendObj.provinceCode = pageBindObj.provinceCode.map(function(blName) {
				return blName.provinceCode;
			});
			sendObj.provinceName = pageBindObj.provinceCode.map(function(blName) {
				return blName.provinceName;
			});

			sendObj.channel = pageBindObj.channel.map(function(blName) {
				return blName.channelCode;
			});
			sendObj.organization = pageBindObj.organization.map(function(blName) {
				return blName.organizationCode;
			});
			sendObj.timeType = pageBindObj.timeType;
			sendObj.diffTime = pageBindObj.diffTime + '';
			//当账期为年或者月的时候，获取的时间是数字格式，转换为字符串时间格式
			if (sendObj.timeType === '5' || sendObj.timeType === '4') {
				sendObj.startTime = pageBindObj.startTime + '-01-01';
				sendObj.endTime = pageBindObj.endTime + '-01-01';
			} else {
				sendObj.startTime = pageBindObj.startTime;
				sendObj.endTime = pageBindObj.endTime;
			}
			sendObj.startTime = CoreService.dateFormat(sendObj.startTime, 'yyyy-MM-dd');
			sendObj.endTime = CoreService.dateFormat(sendObj.endTime, 'yyyy-MM-dd');
			sendObj.seqPro = '0'; //默认省排序  0 省升序  1 省降序  ''不排序
			// sendObj.diffPro = $scope.sendData.diffPro;
			if (sendObj.provinceCode.length !== 0 && sendObj.diffTime === 'false') {
				sendObj.diffPro = '2';
			} else if (sendObj.provinceCode.length !== 0 && sendObj.diffTime === 'true') {
				sendObj.diffPro = '1';
			} else {
				sendObj.diffPro = pageBindObj.diffPro;
			}
			sendObj.seqBus = '';
			if (sendObj.timeType === '4') {
				sumStatisticsFn.splitQuarter(sendObj);
			}
			return sendObj;
		}
	}
	sumStatisticsData.$inject = ['sumStatisticsFn', 'CoreService'];
	function sumStatisticsServe(Restangular, QueryResultService) {
		return {

			//接入渠道查询
			queryChannels: function(params,callback) {
				Restangular.all('sas/common/accessChannelsQuery').post(params).then(callback);
			},
			//机构查询
			queryAgency: function() {
				Restangular.one('sas/common/agencyQuery').get().then(function(res) {
					QueryResultService.agencys = res.data;
				});
				return QueryResultService;
			},
			//交易类型查询
			queryTradeType: function(params,callback) {
				Restangular.all('sas/common/tradeTypeQuery').post(params).then(callback);
			},
			//查询交易总量
			querySumStatistics: function(params, callback) {
				Restangular.all('sas/Omdisplay/sysBusinessStatistics/sumStatisticsQuery').post(params).then(callback);
			}
		};
	}
	sumStatisticsServe.$inject = ['Restangular', 'QueryResultService'];
	function sumStatisticsFn(PublicFn) {
		return {
			splitQuarter : splitQuarter,
			getNames : getNames,
			mySort : mySort,
			fmtDown : fmtDown,
			getEchartsData : getEchartsData,
			giveProCode : giveProCode,
			calculateSummary : calculateSummary,
			getTimeType : getTimeType,
			exportView : exportView,
			getAvgName : getAvgName,
			getCollect : getCollect,
			getTitle: getTitle
		};
		/**
		 * @function [splitQuarter]   选择季度时，页面获取的年和季度是一个字段，如开始时间为:20151
			将它分成开始年为2015，开始季度为1季度
		 * @param  {[object]} send  页面绑定对象
		 */
		function splitQuarter(send) {
			var startYear = send.startTime.substring(0, 4);
			var startQuarter = send.startTime.substring(4, 5);
			var endYear = send.endTime.substring(0, 4);
			var endQuarter = send.endTime.substring(4, 5);
			send.startTime = startYear + '-01-01';
			send.endTime = endYear + '-01-01';
			send.startQuarter = startQuarter;
			send.endQuarter = endQuarter;
		}
		/**
		 * @function [spliceYear] 查询账期为年,页面下钻时，获取页面time并将它组合成相应的格式发送给后端
			在分省情况下，页面time是一个时间区间，如2014_2015，获取这个时间段将它分成开始时间为2014-01-01，
			束时间为2015-01-01。
			不分省情况下，页面time是一个字符串时间，如2014,获取这个时间段将它分成开始时间为2014-01-01.结束时
			间为2014-01-01
		 * @param  {[object]} yearData   页面表格每一行对象
		 * @param  {[object]} downObj    页面查询条件
		 */
		function spliceYear(yearData, downObj) {
			var startYear = yearData.substring(0, 4);
			if (downObj.diffPro === '2') {
				var endYear = yearData.substring(5, 9);
				downObj.startTime = startYear + '-01-01';
				downObj.endTime = endYear + '-01-01';
			} else {
				downObj.startTime = startYear + '-01-01';
				downObj.endTime = startYear + '-01-01';
			}
		}
		/**
		 * @function[spliceQuarter] 查询账期为季,页面下钻时，获取页面time并将它组合成相应的格式发送给后端
			在分省情况下，页面time是一个时间区间，如2014第1季度_2015第1季度，获取这个时间段将它分成开始时间
			为2014-01-01，结束时间为2015-03-01。
			不分省情况下，页面time是一个字符串时间，如2014第1季度,获取这个时间段将它分成开始时间为
			2014-01-01.结束时间2014-03-01
		 * @param  {[object]} quarterData   页面表格每一行对象
		 * @param  {[object]} downObj    页面查询条件
		 */
		function spliceQuarter(quarterData, downObj) {
			//2013第1季度   2013第1季度-2013第2季度
			var startYear = quarterData.substring(0, 4);
			var startQuarter = quarterData.substring(5, 6);
			if (downObj.diffPro === '2') {
				var endYear = quarterData.substring(9, 13);
				var endQuarter = quarterData.substring(14, 15);
				switch (startQuarter) {
					case '1':
						downObj.startTime = startYear + '-01-01';
						break;
					case '2':
						downObj.startTime = startYear + '-04-01';
						break;
					case '3':
						downObj.startTime = startYear + '-07-01';
						break;
					case '4':
						downObj.startTime = startYear + '-10-01';
						break;
				}
				switch (endQuarter) {
					case '1':
						downObj.endTime = endYear + '-03-01';
						break;
					case '2':
						downObj.endTime = endYear + '-06-01';
						break;
					case '3':
						downObj.endTime = endYear + '-09-01';
						break;
					case '4':
						downObj.endTime = endYear + '-12-01';
						break;
				}
			} else {
				switch (startQuarter) {
					case '1':
						downObj.startTime = startYear + '-01-01';
						downObj.endTime = startYear + '-03-01';
						break;
					case '2':
						downObj.startTime = startYear + '-04-01';
						downObj.endTime = startYear + '-06-01';
						break;
					case '3':
						downObj.startTime = startYear + '-07-01';
						downObj.endTime = startYear + '-09-01';
						break;
					case '4':
						downObj.startTime = startYear + '-10-01';
						downObj.endTime = startYear + '-12-01';
						break;
				}
			}
		}
		/**
		 * @function[spliceMonth] 查询账期为月,页面下钻时，获取页面time并将它组合成相应的格式发送给后端
			在分省情况下，页面time是一个时间区间，如201401_201501，获取这个时间段将它分成开始时间为2014-01-01,
			结束时间为2015-01-01。
		  不分省情况下，页面time是一个字符串时间，如201401,获取这个时间段将它分成开始时间为2014-01-01.
		  结束时间2014-01-31
		 * @param  {[object]} monthData  页面表格每一行对象
		 * @param  {[object]} downObj    页面查询条件
		 */
		function spliceMonth(monthData, downObj) {
			//201301-201301
			var year = monthData.substring(0, 4);
			var month = monthData.substring(4, 6);
			var nowDate = new Date(year, month, 0);
			downObj.startTime = year + '-' + month + '-01';
			if (downObj.diffPro === '2') {
				var endYear = monthData.substring(7, 11);
				var endMonth = monthData.substring(11, 13);
				var endDate = new Date(endYear, endMonth, 0);
				downObj.endTime = endYear + '-' + endMonth + endDate.getDate();
			} else {
				downObj.endTime = year + '-' + month + '-' + nowDate.getDate();
			}
		}
		/**
		 * [getNames] 获取省份下拉框选项 当页面分时刻情况下，默认显示'全部(汇总)'，
		 * @param  {[array]} series      页面选择了多少省份组成的数组
		 * @param  {[string]} propertyName  页面省份下拉框省份字段名  provinceName
		 * @param  {[array]} objArr      下拉框中所有的省份数组
		 * @return {[string]} 下拉框显示文字
		 */
		function getNames(series, propertyName, objArr, diffTime) {
			if (angular.isArray(series)) {
				if (series.length === objArr.length) {
					if (diffTime === true) {
						return '全部(汇总)';
					} else {
						return '全部(分省)';
					}
				}
				var arrName = series.map(function(item) {
					if (!item) {
						return undefined;
					}
					return item[propertyName];
				});
				return arrName.join(',');
			} else {
				return series[propertyName];
			}
		}
		/**
		 * @function [mySort] 对省份或者业务量进行排序
		 * @param  {[boolean]} proOrBus  区分升序还是降序
		 * @param  {[array]} item         页面省份数据
		 * @param  {[string]} propertyName 单击省份排序时为'provinceName' 业务量排序时为'businessNum'
		 */
		function mySort(proOrBus, item, propertyName) {
			if (proOrBus) {
				item.sort(function(a, b) {
					return Number(a[propertyName]) < Number(b[propertyName]) ? -1 : 1;
				});
			} else {
				item.sort(function(a, b) {
					return Number(a[propertyName]) < Number(b[propertyName]) ? 1 : -1;
				});
			}
		}
		/**
		 * @function [fmtDown] 下钻时，改变查询的值
		 * @param  {[object]} downData 下钻时表格行对象
		 * @param  {[object]} bindObj   页面查询条件
		 */
		function fmtDown(downData, bindObj) {
			var type = bindObj.timeType;
			switch (type) {
				case '5': //年 下钻到季
					bindObj.timeType = '4';
					spliceYear(downData.time, bindObj);
					bindObj.startQuarter = '1';
					bindObj.endQuarter = '4';
					break;
				case '4': //季 下钻到月
					bindObj.timeType = '3';
					bindObj.startQuarter = '';
					bindObj.endQuarter = '';
					spliceQuarter(downData.time, bindObj);
					break;
				case '3': //月 下钻到日
					bindObj.timeType = '1';
					spliceMonth(downData.time, bindObj);
					break;
				case '1':
					bindObj.timeType = 't';
					break;
			}
		}
		//显示相应的均值名称,如账期为年的时候，均值的名称为年均值
		function showAvgName(data, proState, bool) {
			var avgName = '';
			var type = data.timeType;
			if (data.diffTime === 'true') {
				avgName = '时';
			} else if (bool && proState) {
				avgName = '省';
			} else {
				switch (type) {
					case '5': //年 下钻到季
						avgName = '年';
						break;
					case '4': //季 下钻到月
						avgName = '季';
						break;
					case '3': //月 下钻到日
						avgName = '月';
						break;
					default:
						avgName = '日';
				}
			}
			return avgName;
		}
		//echarts图所需要的数据
		function showEcharts(ecText, echartsTooltip, echartsXAxis, echartsSeries, legendData, echartsYAxis) {
			return {
				title: {
					text: ecText,
					x: 'center'
				},
				animation: false,
				tooltip: echartsTooltip,
				dataZoom: {
					show: true,
					realtime: true
				},
				grid: {
					x2: 130
				},
				legend: {
					data: legendData,
					orient: 'vertical',
					x: 'right',
					y: 'center'
				},
				xAxis: echartsXAxis,
				yAxis: echartsYAxis,
				series: echartsSeries
			};
		}
		//天猫业务量以百万为单位 交易金额以亿为单位
		//移动商城和银行总对总业务量以万为单位  交易金额以千万为单位
		function dataFor(sd, items, temp, wdName) {
			angular.forEach(temp.xDataArr, function(tr) {
				temp.businessNum[tr] = 0;
				temp.orderAmount[tr] = 0;
			});
			if (sd.tradeStateCode.length === 0) {
				if (sd.businessLine.indexOf('1') !== -1 || sd.businessLine.length === 0) {
					angular.forEach(items, function(item) {
						temp.businessNum[item[wdName]] = Number((item.successTotal / 1000000).toFixed(2));
						temp.orderAmount[item[wdName]] = Number((item.orderTotal / 100000000).toFixed(2));
					});
				} else {
					angular.forEach(items, function(item) {
						temp.businessNum[item[wdName]] = Number((item.successTotal / 10000).toFixed(2));
						temp.orderAmount[item[wdName]] = Number((item.orderTotal / 10000000).toFixed(2));
					});
				}
			} else {
				if (sd.businessLine.indexOf('1') !== -1 || sd.businessLine.length === 0) {
					angular.forEach(items, function(item) {
						temp.businessNum[item[wdName]] = Number((item.businessNum / 1000000).toFixed(2));
						temp.orderAmount[item[wdName]] = Number((item.orderAmount / 100000000).toFixed(2));
					});
				} else {
					angular.forEach(items, function(item) {
						temp.businessNum[item[wdName]] = (item.businessNum / 10000).toFixed(2);
						temp.orderAmount[item[wdName]] = (item.orderAmount / 10000000).toFixed(2);
					});
				}
			}
		}
		function getTitle(send){
			var title = '';
			//业务线名称
			var businessLineName = send.businessLineName.length === 0 ? '统一支付' : send.businessLineName.toString();
			var diffTime = send.diffTime === 'true' ? '分时刻' : '';
			var diffPro = send.diffPro === '2' ? '分省' : '';
			title = businessLineName + diffPro + '系统业务量'+ diffTime +'统计分析';
			var timeTitle = PublicFn.fmtDateTitle(send,'timeType');
			return timeTitle + title;
		}
		/**
		 * [getEchartsData]  设置echarts所需要的各种数据 当业务线长度为0或者业务线是天猫的时候，echarts图
		 * 的左边y轴交易金额单位为亿元，右边y轴业务量单位为百万笔。当业务线为移动商城或者银行总对总的时候
		 * echarts图的左边y轴交易金额单位为百万元，右边y轴业务昌单位为万笔。
		 * @param  {object} sd     查询条件
		 * @param  {array} items   查询获取的数组
		 */
		function getEchartsData(sd, items) {
			var echartsSeries = [];
			var seriesData = [];
			var businessNum = [];
			var orderAmount = [];
			var temp = {
				businessNum: {},
				orderAmount: {},
				xDataArr: []
			};
			var echartsXAxis = [];
			var echartsYAxis = [];
			var echartsTooltip = {};
			if (sd.businessLine.length === 0 || sd.businessLine.indexOf('1') !== -1) {
				echartsYAxis = [{
					type: 'value',
					name: '交易金额(单位:亿元)'
				}, {
					type: 'value',
					splitLine: false,
					name: '业务量(单位:百万笔)'
				}];
				echartsTooltip = {
					show: true,
					formatter: function(params) {
						var show = params.name + ' </br>' + params.seriesName + ':' + params.value;
						if (params.seriesName === '业务量') {
							return show + '(百万笔)';
						} else {
							return show + '(亿元)';
						}
					}
				};
			} else {
				echartsYAxis = [{
					type: 'value',
					name: '交易金额(单位:千万元)'
				}, {
					type: 'value',
					splitLine: false,
					name: '业务量(单位:万笔)'
				}];
				echartsTooltip = {
					show: true,
					formatter: function(params) {
						var show = params.name + ' </br>' + params.seriesName + ':' + params.value;
						if (params.seriesName === '业务量') {
							return show + '(万笔)';
						} else {
							return show + '(千万元)';
						}
					}
				};
			}
			//在分省的情况下默认以省份为x坐标显示，否则以时间显示
			if (sd.diffPro === '2') {
				angular.forEach(items, function(item) {
					temp.xDataArr.push(item.provinceName);
				});
				echartsXAxis = [{
					axisLabel: {
						show: true,
						rotate: 52,
						textStyle: {
							color: 'black',
							fontWeight: 'bold'
						}
					},
					data: temp.xDataArr
				}];
				dataFor(sd, items, temp, 'provinceName');
			} else {
				if (sd.timeType === '4' && sd.diffTime === 'false') {
					angular.forEach(items, function(item) {
						var year = item.time.substring(0, 4);
						var quarter = item.time.substring(5, 6);
						item.time = year + '第' + quarter + '季度';
						temp.xDataArr.push(item.time);
					});
				} else {
					angular.forEach(items, function(item) {
						temp.xDataArr.push(item.time);
					});
				}
				echartsXAxis = [{
					type: 'category',
					data: temp.xDataArr
				}];
				dataFor(sd, items, temp, 'time');
			}
			angular.forEach(temp.xDataArr, function(xd){
				orderAmount.push(temp.orderAmount[xd]);
				businessNum.push(temp.businessNum[xd]);
			});
			seriesData.push(orderAmount);
			seriesData.push(businessNum);
			var legendData = ['交易金额', '业务量'];
			echartsSeries = [{
				name: legendData[1],
				type: 'bar',
				markPoint: {
					data: [{
						type: 'max',
						name: legendData[1] + '最大值'
					}]
				},
				yAxisIndex: 1,
				data: seriesData[1]
			}, {
				name: legendData[0],
				type: 'line',
				smooth: true,
				markPoint: {
					data: [{
						type: 'max',
						name: legendData[0] + '最大值'
					}]
				},
				data: seriesData[0]
			}];
			return showEcharts(sd.title, echartsTooltip, echartsXAxis, echartsSeries, legendData, echartsYAxis);
		}
		//给每个省份code
		function giveProCode(send, items, provinces) {
			angular.forEach(items.data, function(rd) {
				angular.forEach(provinces, function(p) {
					if (rd.provinceName === p.provinceName) {
						rd.provinceCode = p.provinceCode;
					}
				});
				if (rd.tradeStateName === '00') {
					rd.tradeStateName = '充值成功';
				} else if (rd.tradeStateName === '01') {
					rd.tradeStateName = '交易失败';
				} else {
					rd.tradeStateName = '全部';
				}
			});
		}
		/**
		 * @function [calculateSummary] 计算交易状态为成功或者失败时的汇总和
		 * @param  {[array]} data        后端返回的查询结果
		 */
		function calculateSummary(data) {
			var sum = {
				businessNum: 0,
				orderAmount: 0,
				rechargeAmount: 0
			};
			angular.forEach(data, function(item) {
				sum.businessNum += item.businessNum;
				sum.orderAmount += item.orderAmount;
				sum.rechargeAmount += item.rechargeAmount;
			});
			sum.orderAmount = sum.orderAmount.toFixed(2);
			sum.rechargeAmount = sum.rechargeAmount.toFixed(2);
			return sum;
		}
		/**
		 * @function [getCollect]  交易状态为全部时的汇总
		 * @param  {[type]} result [description]
		 * @return {[type]}        [description]
		 */
		function getCollect(result){
			var collect = [0, 0, 0, 0, 0, 0, 0, 0, 0];
			angular.forEach(result.data, function(rd){
				rd.successTotal = rd.busSuccess + rd.busFail;
				collect[0] += rd.successTotal;
				collect[1] += rd.busSuccess;
				collect[2] += rd.busFail;
				rd.orderTotal = rd.orderSuccess + rd.orderFail;
				collect[3] += rd.orderTotal;
				collect[4] += rd.orderSuccess;
				collect[5] += rd.orderFail;
				rd.rechargeTotal = rd.rechargeSuccess + rd.rechargeFail;
				collect[6] += rd.rechargeTotal;
				collect[7] += rd.rechargeSuccess;
				collect[8] += rd.rechargeFail;
			});
			return collect;
		}
		//单击返回按钮时,改变账期
		function getTimeType(type) {
			var timeType = '';
			switch (type) {
				case 't': //每日返回到日
					timeType = '1';
					break;
				case '1': //每日返回到月
					timeType = '3';
					break;
				case '3': //月 返回到季
					timeType = '4';
					break;
				default:
					timeType = '5';
					break;
			}
			return timeType;
		}
		//导出
		function exportView(backState, myEcharts, send, sendOut) {
			send.base64s = [];
			sendOut.base64s = [];
			var outData = '';
			var b = myEcharts.getDataURL('png');
			if (backState) {
				sendOut.base64s.push(b.split(',')[1]);
				outData = JSON.stringify(sendOut);
			} else {
				send.base64s.push(b.split(',')[1]);
				outData = JSON.stringify(send);
			}
			return outData;
		}
		/**
		 * @function [getAvgName] 获取均值的名字,当以分省查询,账期为年时,均值名字是'省',单击省下钻后
		 * 均值名字依次为  '年','季','月','日','日'.如果以分时刻查询,均值名字为 '时';
		 * 获取均值名字后并增加avg字段发送给后端(方便后端导出均值名字和前端页面显示一样)
		 * @param  {[object]} send    发送给后端的查询条件
		 * @param  {[string]} proState
		 * @return {[string]}      均值的名字,
		 *
		 */
		function getAvgName(send, proState) {
			var avgName = '';
			if (send.diffPro === '2') {
				avgName = showAvgName(send, proState, true);
			} else {
				avgName = showAvgName(send, proState);
			}
			send.avg = avgName;
			return avgName;
		}
	}
	sumStatisticsFn.$inject = ['PublicFn'];
})();